package com.SmartEdu.controller;

import com.SmartEdu.dto.User;
import com.SmartEdu.register.VerifyCodeGenerator;
import com.SmartEdu.service.UserService;
import com.SmartEdu.vo.RestBean;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.http.HttpRequest;

@RestController
@RequestMapping("/api/auth")
@Tag(name = "用户注册",description = "处理用户注册相关数据")
public class RegisterController {
    @Resource
    UserService service;

    @Value("${email.emailName}")
    String emailName;
    @Resource
    JavaMailSender sender;

    @Operation(summary = "验证码接口，传入用户邮箱，向用户邮箱发送一个六位纯数字字符串验证码" )
    @GetMapping("/verification")
    public String getVerificationCode(String email){
        //获取验证码
        String verificationCode = VerifyCodeGenerator.generateVerificationCode();
        System.out.println(email);
        System.out.println("验证码为："+verificationCode);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("登录验证码");
        message.setText("验证码为："+verificationCode);
        message.setTo(email);
        message.setFrom(emailName);
        sender.send(message);
        return RestBean.success(verificationCode).asJsonString();
    }

    @Operation(summary = "注册接口" )
    @PostMapping("/register")
    public String login(User registerUser, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = registerUser.getEmail();

            //查询数据库是否存在该用户
            User user = service.getById(registerUser.getEmail());
            if(user!=null){
                return RestBean.forbidden("用户已存在").asJsonString();
            }else{
                service.save(registerUser);
            }
            request.setAttribute("email",registerUser.getEmail());
            request.setAttribute("password",registerUser.getPassword());
            request.getRequestDispatcher("/api/auth/login").forward(request,response);
        return RestBean.success().asJsonString();
    }
}
